<template>
  <div class="app-pro-basicLayout-content-wrap">
    <div class="app-pro-pages-content">
      <div class="app-pro-table-search">
        <el-form :inline="true" :model="formInline" ref="formInline" label-width="80px" size="small" class="form-flex-item">
          <el-row :gutter="20">
            <el-col :xs="12" :sm="10" :md="8" :lg="6">
              <el-form-item label="빠른검색" prop="name">
                <el-input v-model="formInline.name" placeholder="키워드검색"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="10" :md="8" :lg="6">
              <el-form-item label="기업이름" prop="unit_name">
                <el-input v-model="formInline.unit_name" placeholder="검색 업체 키워드"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="10" :md="8" :lg="6">
              <el-form-item label="역할" prop="role_id">
                <el-select v-model="formInline.role_id" placeholder="역할을 선택해 주세요.">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="6" :sm="6" :md="6" :lg="6">
              <el-form-item>
                <el-button type="primary" size="small" @click="handleSearch">검색</el-button>
                <el-button size="small" @click="resetForm('formInline')">초기화</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="app-pro-pages-table">
        <div class="main-card">
          <div class="main-table-toolbar">
            <div class="main-table-toolbar-title">
              <div class="main-table-toolbar-title-only">사용자</div>
            </div>
            <div class="main-table-toolbar-option">
              <el-button type="primary" size="mini" icon="el-icon-plus" style="margin-right:5px" @click="confirmAddUser">추가</el-button>
              <!-- <el-link :underline="false" class="main-table-toolbar-item-icon">
                <el-tooltip class="item" effect="dark" content="다운로드" placement="top">
                  <i class="el-icon-download"></i>
                </el-tooltip>
              </el-link> -->
              <!-- <el-link :underline="false" class="main-table-toolbar-item-icon">
                <el-tooltip class="item" effect="dark" content="초기화" placement="top">
                  <i @click="getUserList()" class="el-icon-refresh-right"></i>
                </el-tooltip>
              </el-link> -->
            </div>
          </div>
          <div class="main-table-wrapper" style="padding: 0">
            <my-table
              :columns="columns"
              :data="data"
              :loading="loading"
              :pagination="pagination"
              :showIndex="true"
              :showSelection="true"
              :cellStyle="{padding: '6px 0'}"
              :headerCellStyle="{background:'rgba(247, 133, 2, 1)',color:'#fff'}"
              @emitSelection="emitSelection"
              @currentChange="currentChange">
              <template v-slot:status="slotProps">
                <el-tag v-if="!slotProps.callback.row.deleted_at" effect="dark" size="small">사용중</el-tag>
                <el-tag v-else type="danger" effect="dark" size="small">탈퇴</el-tag>
              </template>
              <template v-slot:operation="slotProps">
                <el-button
                  v-if="!slotProps.callback.row.deleted_at"
                  @click.native.prevent="handleEdit(slotProps.callback.row)"
                  type="text">
                  수정
                </el-button>
                <el-button
                  v-else
                  @click.native.prevent="handleEdit(slotProps.callback.row)"
                  type="text"
                  style="color:#e6a23c">
                  회복
                </el-button>
                <!-- <el-divider direction="vertical"></el-divider> -->
                <el-popconfirm
                  title="삭제하시겠습니까"
                  @onConfirm="handleDeleteUser(slotProps.callback.row.id)"
                  :confirmButtonText="'확인'|language"
                  :cancelButtonText="'취소'|language"
                >
                  <el-button
                    v-if="slotProps.callback.row.deleted_at"
                    slot="reference"
                    type="text"
                    style="padding-left:15px;color:#f56c6c">
                    삭제
                  </el-button>
                </el-popconfirm>
              </template>
            </my-table>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      :title="dialogForm.title"
      custom-class="dialog-content"
      :visible.sync="dialogForm.dialogVisible"
      :destroy-on-close="true"
      top="5%"
      width="550px">
      <div class="dialog-body-content">
        <form-page
          :ref-obj.sync="formInfo.ref"
          :data="formInfo.data"
          :field-list="formInfo.fieldList"
          :rules="formInfo.rules"
          :label-width="formInfo.labelWidth"
          @handleEventChange="handleEventChange"
          :list-type-info="listTypeInfo">
        </form-page>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogForm.dialogVisible = false">취소</el-button>
        <el-button size="small" type="primary" @click="handleSubmitUser">확인</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mergeObjOfValue, deepClone } from '@/utils'
import { validatePhone } from '@/utils/validate'
import FormPage from '_c/FormPage'
import myTable from '_c/Table'
import * as userApi from '@/api/setting/user'
import * as roleApi from '@/api/setting/role'
const formInfoData = {
  id: '',
  name: '',
  phone: '',
  email: '',
  role_id: '',
  unit_id: '',
  password: '',
  password_confirmation: ''
}
const validateEMail = (rule, value, callback) => {
  // eslint-disable-next-line
  const reg = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/
  if (value === '' || value === undefined || value === null) {
    callback()
  } else {
    if (!reg.test(value)) {
      callback(new Error('정확한 우편함을 입력해 주십시오.'))
    } else {
      callback()
    }
  }
}
export default {
  name: 'setting-user',
  data () {
    return {
      formInline: {
        name: '',
        unit_name: '',
        role_id: ''
      },
      options: [],
      columns: [{
        label: '상태',
        prop: '',
        width: 80,
        slot: 'status'
      }, {
        label: '유저이름',
        prop: ''
      }, {
        label: '유저이름',
        prop: 'name'
      }, {
        label: '유저이름',
        prop: 'name'
      }, {
        label: '이메일',
        prop: 'email'
      }, {
        label: '연락처',
        prop: 'phone'
      }, {
        label: '역할',
        prop: 'has_one_role.name'
      }, {
        label: '기업이름',
        prop: 'has_one_unit.name'
      }, {
        label: '관리',
        prop: '',
        width: 160,
        align: 'left',
        slot: 'operation'
      }],
      data: [],
      pagination: {
        currentPage: 1,
        pageSize: 15
      },
      selectionData: [],
      loading: true,
      dialogForm: {
        dialogVisible: false,
        title: '추가'
      },
      listTypeInfo: {
        role_id: []
      },
      formInfo: {
        ref: null,
        data: formInfoData,
        fieldList: [
          { label: '유저이름', value: 'name', width: '260', type: 'input', className: 'el-form-block', required: true },
          { label: '이메일', value: 'email', width: '260', type: 'input', className: 'el-form-block', validator: validateEMail },
          { label: '휴대폰 번호', value: 'phone', width: '260', type: 'input', className: 'el-form-block', required: true, validator: validatePhone },
          { label: '역할', value: 'role_id', width: '260', type: 'select', className: 'el-form-block', required: true, list: 'role_id' },
          { label: '기업이름', value: 'unit_id', width: '260', type: 'select', className: 'el-form-block', required: true, list: 'unit_id' },
          { label: '비밀번호', value: 'password', width: '260', type: 'input', className: 'el-form-block', required: true },
          { label: '비밀번호 확인', value: 'password_confirmation', width: '260', type: 'input', className: 'el-form-block', required: true, event: 'changePasswordConfirmation' }
        ],
        rules: {},
        labelWidth: '150px'
      }
    }
  },
  components: {
    myTable,
    FormPage
  },
  mounted () {
    this.formInfo.data = deepClone(formInfoData)
    this.getUserList()
    this.getRoleList()
    this.initRules()
  },
  methods: {
    initRules () {
      const formInfo = this.formInfo
      formInfo.rules = this.$initRules(formInfo.fieldList)
    },
    getRoleList () {
      roleApi.getRoleList().then(res => {
        this.options = this.listTypeInfo.role_id = res.map(item => {
          return {
            value: item.id,
            label: item.name
          }
        })
      })
    },
    getUserList () {
      const data = {
        ...this.formInline,
        page: this.pagination.currentPage,
        per: this.pagination.pageSize
      }
      this.loading = true
      userApi.getUserList(data).then(res => {
        this.loading = false
        this.data = res.data
        this.pagination.total = res.meta.pagination.total
      })
    },
    handleDeleteUser (id) {
      userApi.deleteUser({ id }).then(res => {
        this.getUserList()
      })
    },
    confirmAddUser () {
      this.dialogForm.title = '추가'
      mergeObjOfValue(this.formInfo.data, formInfoData)
      this.dialogForm.dialogVisible = true
    },
    handleSubmitUser () {
      if (this.formInfo.data.id) {
        userApi.updateUser(this.formInfo.data).then(res => {
          this.$message({
            message: '수정되였습니다',
            type: 'success'
          })
        })
      } else {
        userApi.ceaterUser(this.formInfo.data).then(res => {
          this.$message({
            message: '삭제되였습니다',
            type: 'success'
          })
        })
      }
    },
    handleEdit (rowData) {
      this.dialogForm.title = '수정'
      mergeObjOfValue(this.formInfo.data, rowData)
      this.dialogForm.dialogVisible = true
    },
    handleSearch () {
      this.pagination.currentPage = 1
      this.getUserList()
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.getUserList()
    },
    emitSelection (val) {
      this.selectionData = val
    },
    currentChange (val) {
      this.pagination.currentPage = val
      this.getUserList()
    },
    handleEventChange (event, data) {
      switch (event) {
        case 'changePasswordConfirmation': {
          if (this.formInfo.data.password === '') {
            this.$message({
              message: '새로운 비밀번호를 입력해주세요.',
              type: 'warning'
            })
            this.formInfo.data.password_confirmation = ''
          } else if (this.formInfo.data.password !== this.formInfo.data.password_confirmation) {
            this.$message({
              message: '비밀번호와 비밀번호 확인이 다릅니다.',
              type: 'error'
            })
            this.formInfo.data.password_confirmation = ''
          }
          break
        }
      }
    }
  }
}
</script>
